package com.emm.yixun.website.controller.estate;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.emm.yixun.common.enums.HouseTypeEnum;
import com.emm.yixun.common.model.Department;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.Role;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.ApartmentModel;
import com.emm.yixun.common.model.dto.CarModel;
import com.emm.yixun.common.model.dto.DepartmentDto;
import com.emm.yixun.common.model.dto.ImportlogDto;
import com.emm.yixun.common.model.dto.RoleDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.dto.VillaModel;
import com.emm.yixun.common.model.enums.ExcelTypeEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.PasswordUtil;
import com.emm.yixun.common.utils.SequencesGenerator;
import com.emm.yixun.common.utils.Trans2PinYin;
import com.emm.yixun.estate.service.ImportExcelServiceFacade;
import com.emm.yixun.estate.service.ImportlogServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.system.service.DepartmentServiceFacade;
import com.emm.yixun.system.service.RoleServiceFacade;
import com.emm.yixun.system.service.UserRoleServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.constant.ConstantConfig;
import com.emm.yixun.website.task.utils.ExcelReader;

/**
 * 类描述： 项目信息批量导入 创建者： ThinkPad 项目名称： emm-website 创建时间： 2016年5月25日 上午11:22:48 版本号： v1.0
 */
@RequestMapping(value = "/estate/import/")
@Controller
public class ProjectImportController {
	@Resource
	private ProjectServiceFacade projectServiceFacade;

	@Resource
	private ImportExcelServiceFacade importExcelServiceFacade;

	@Resource
	private DepartmentServiceFacade departmentServiceFacade;

	@Resource
	private RoleServiceFacade roleServiceFacade;

	@Resource
	private UserServiceFacade userServiceFacade;

	@Resource
	private UserRoleServiceFacade userRoleServiceFacade;

	
	@Resource
	private ImportlogServiceFacade importlogServiceFacade;
	
	@Autowired
	private ConstantConfig constantConfig;
	//estate:import:importExcel 
	//estate:import:downLoadExcel

	/**
	 * 方法描述 : 跳转导入页面 创建者：ThinkPad 项目名称： emm-website 类名： ProjectImportController.java 版本： v1.0 创建时间： 2016年5月25日
	 * 上午11:38:44
	 * 
	 * @param request
	 * @param id
	 * @return ModelAndView
	 */
	@RequestMapping(value = "index")
	public ModelAndView index(HttpServletRequest request, Long id) {
		Response<Project> info = projectServiceFacade.findById(id);
		if (info.getEntity() != null) {
			return new ModelAndView("estate/import/index").addObject("project", info.getEntity()).addObject("menu",
					request.getParameter("menu")).addObject("fatTemplet", constantConfig.getFatTemplet()).addObject("villaTemplet", constantConfig.getVillaTemplet()).addObject("parkingTemplet", constantConfig.getParkingTemplet());
		}
		return null;
	}
	
	/**
	 * 方法描述 : 跳转导入页面 创建者：ThinkPad 项目名称： emm-website 类名： ProjectImportController.java 版本： v1.0 创建时间： 2016年5月25日
	 * 上午11:38:44
	 * 
	 * @param request
	 * @param id
	 * @return ModelAndView
	 */
	@RequestMapping(value = "indexLC")
	public ModelAndView indexLC(HttpServletRequest request, Long id) {
		Response<Project> info = projectServiceFacade.findById(id);
		if (info.getEntity() != null) {
			return new ModelAndView("estate/import/indexLC").addObject("project", info.getEntity()).addObject("menu",
					request.getParameter("menu")).addObject("fatTemplet", constantConfig.getFatTemplet()).addObject("villaTemplet", constantConfig.getVillaTemplet()).addObject("parkingTemplet", constantConfig.getParkingTemplet());
		}
		return null;
	}

	/**
	 * 方法描述 : 导入EXCEL 创建者：ThinkPad 项目名称： emm-website 类名： ProjectImportController.java 版本： v1.0 创建时间： 2016年5月25日
	 * 下午3:39:50
	 * 
	 * @param id
	 * @param multipartFile
	 * @param request
	 * @return java.util.Map<String, String>
	 */
	@RequestMapping(value = "importExcel")
	public @ResponseBody
	java.util.Map<String, String> importHouseInfo(Long id, HttpServletRequest request, String type) {
		java.util.Map<String, String> map = new HashMap<String, String>();
		
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> multipartFile = multipartRequest.getFiles("multipartFile");
			@SuppressWarnings("resource")
			Workbook wb = new XSSFWorkbook(multipartFile.get(0).getInputStream());
			Sheet xssfSheet = wb.getSheetAt(0);
			Response<Project> project = projectServiceFacade.findById(id);
			String result = vaildExcelType(xssfSheet, type);
			if(result!=null){
				map.put("result", result);
				return map;
			}
			User user = ShiroUtil.getCurrentUser();
			if (!project.isSuccess()) {
				return map;
			} else {
				if (type.equals(HouseTypeEnum.HOUSETYPE_0.getCode())) {
					List<Object> list = getExcelValue(xssfSheet, new ApartmentModel());
					// 导入组团信息,判断导入的是哪种模版
					List<ApartmentModel> model = new ArrayList<ApartmentModel>();
					// 类型转换
					for (int i = 0; i < list.size(); i++) {
						ApartmentModel convertedObj = (ApartmentModel) list.get(i);
						model.add(convertedObj);
					}
					map = importExcelServiceFacade.importApartment(model, id, user);
				} else if (type.equals(HouseTypeEnum.HOUSETYPE_1.getCode())) {
					List<Object> list = getExcelValue(xssfSheet, new VillaModel());
					List<VillaModel> model = new ArrayList<VillaModel>();
					for (int i = 0; i < list.size(); i++) {
						VillaModel convertedObj = (VillaModel) list.get(i);
						model.add(convertedObj);
					}
					map = importExcelServiceFacade.importVilla(model, id, user);
				} else if (type.equals(HouseTypeEnum.HOUSETYPE_2.getCode())) {
					List<Object> list = getExcelValue(xssfSheet, new CarModel());
					List<CarModel> model = new ArrayList<CarModel>();
					for (int i = 0; i < list.size(); i++) {
						CarModel convertedObj = (CarModel) list.get(i);
						model.add(convertedObj);
					}
					map = importExcelServiceFacade.importCarInfo(model, id, user);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			String no = SequencesGenerator.getUUID("BTN");
			map.put("result", no);
			saveImportLog("导入错误", "0", "请下载模版填写数据,导入!", 0L, no, ShiroUtil.getCurrentUser());
		}
		return map;
	}

	/**
	 * 方法描述 : 获取EXCEL内容 创建者：ThinkPad 项目名称： emm-website 类名： ProjectImportController.java 版本： v1.0 创建时间： 2016年5月25日
	 * 下午3:58:27
	 * 
	 * @param xssfSheet
	 * @param model
	 * @return List<String>
	 */
	public List<Object> getExcelValue(Sheet xssfSheet, Object model) throws Exception {
		List<Object> arraylist = new ArrayList<Object>();
		// 获取总行数
		Class<?> tClass = model.getClass();
		Field[] fields = tClass.getDeclaredFields();
		Integer totalRow = xssfSheet.getPhysicalNumberOfRows();
		for (int i = 1; i < totalRow; i++) {
			Integer totalCell = (int) xssfSheet.getRow(i).getLastCellNum();
			for (int j = 0; j < totalCell; j++) { // 实体对象的字段值对应EXCEL列数
				String name = fields[j].getName(); // 获取属性的名字
				name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set
				Method m = model.getClass().getMethod("get" + name);
				m = model.getClass().getMethod("set" + name, String.class);
				Object objValue = ExcelReader.getCell(xssfSheet.getRow(i).getCell(j));
				m.invoke(model, objValue == null ? null : objValue.toString());
			}
			if (model instanceof com.emm.yixun.common.model.dto.ApartmentModel) {
				arraylist.add(model);
				model = new ApartmentModel();
			} else if (model instanceof VillaModel) {
				arraylist.add(model);
				model = new VillaModel();
			} else if (model instanceof CarModel) {
				arraylist.add(model);
				model = new CarModel();
			}

		}
		return arraylist;
	}

	/**
	 * 方法描述 : 导入部门和员工信息 创建者：ThinkPad 项目名称： emm-website 类名： ProjectImportController.java 版本： v1.0 创建时间： 2016年6月21日
	 * 下午2:08:19
	 * 
	 * @param request
	 * @return AjaxRes
	 */
	@RequestMapping(value = "importExcelInfo")
	public @ResponseBody
	Map<String, Object> importExcelInfo(HttpServletRequest request, Integer type) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<Integer, List<String>> res = new HashMap<Integer, List<String>>();
		try {
			File file = new File("D:\\abc-ny.xlsx");
			@SuppressWarnings("resource")
			Workbook wb = new XSSFWorkbook(file);
			Sheet xssfSheet = wb.getSheetAt(type);
			// 部门
			Integer totalRow = xssfSheet.getPhysicalNumberOfRows();
			for (int i = 1; i < totalRow; i++) {
				Integer totalCell = (int) xssfSheet.getRow(i).getLastCellNum();
				List<String> list = new ArrayList<String>();
				for (int j = 0; j < totalCell; j++) {
					Object objValue = ExcelReader.getCell(xssfSheet.getRow(i).getCell(j));
					list.add(objValue.toString());
				}
				res.put(i, list);
			}
			// 遍历map
			for (Map.Entry<Integer, List<String>> entry : res.entrySet()) {
				List<String> list = entry.getValue();
				if (type == 0) {
					saveDep(list);
				} else {
					try {
						saveUserInfo(list);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			map.put("success", new Date());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public void saveDep(List<String> list) {
		DepartmentDto dto = new DepartmentDto();
		dto.setDepartmentName(list.get(2));
		User user = ShiroUtil.getCurrentUser();
		// 创建父节点
		DepartmentDto entity = new DepartmentDto();
		entity.setDepartmentCode(list.get(4));
		entity.setDepartmentName(list.get(1));

		entity.setSort("1");
		entity.setRemark("系统导入");
		entity.setMerchantId(user.getMerchantId());
		entity.setCreateUserId(user.getId());
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setDelFlag("0");
		
		departmentServiceFacade.save(entity);
	}

	public void saveUserInfo(List<String> list) {
		RoleDto roleDto = new RoleDto();
		roleDto.setRoleName(list.get(10));
		ResponseList<Role> roleList = roleServiceFacade.findByDto(roleDto);
		Long roleId = null;
		Long departId = null;
		User user = ShiroUtil.getCurrentUser();
		if (roleList.isSuccess() && roleList.getEntity() != null) {
			roleId = roleList.getEntity().get(0).getId();
		} else {
			RoleDto entity = new RoleDto();
			entity.setRoleName(list.get(10));
			entity.setRoleIndexPage("1");
			entity.setMerchantId(user.getMerchantId());
			entity.setCreateUserId(user.getId());
			entity.setUpdateTime(new Date());
			entity.setDelFlag("0");
			entity.setRemark("系统导入");
			roleId = roleServiceFacade.save(entity).getEntity().getId();
		}
		DepartmentDto depart = new DepartmentDto();
		depart.setDepartmentName(list.get(2));
		ResponseList<Department> departList = departmentServiceFacade.findByDto(depart);
		if (departList.isSuccess() && departList.getEntity() != null) {
			departId = departList.getEntity().get(0).getId();
		}
		// 创建员工
		String phone=list.get(6);
		if(phone.indexOf(".")!=-1){
			phone=phone.split("\\.")[0];
		}
		//判断手机号重复
		UserDto userDto=new UserDto();
		userDto.setUserPhone(phone);
		ResponseList<User> userList=userServiceFacade.findByDto(userDto);
		if(userList.isSuccess() && null!=userList.getEntity() && userList.getEntity().size()>0){
			return;
		}
		UserDto dtoEntity = new UserDto();
		dtoEntity.setUserAccount(Trans2PinYin.trans2PinYin(list.get(3)));
		dtoEntity.setUserName(list.get(3));
		dtoEntity.setUserPassword(PasswordUtil.md5Hex("x1234567"));
		dtoEntity.setUserPhone(list.get(6));
		dtoEntity.setBirthday(java.sql.Date.valueOf(list.get(8)));
		dtoEntity.setEntryTime(java.sql.Date.valueOf(list.get(9)));
		dtoEntity.setUserStatus("0");
		dtoEntity.setIsAdmin("0");
		dtoEntity.setUserDepartmentId(departId);
		dtoEntity.setRoleId(roleId);
		dtoEntity.setRemark("系统导入");
		dtoEntity.setMerchantId(user.getMerchantId());
		dtoEntity.setCreateUserId(user.getId());
		dtoEntity.setUpdateTime(new Date());
		dtoEntity.setDelFlag("0");
		dtoEntity.setCreateTime(new Date());
		userServiceFacade.save(dtoEntity).getEntity().getId();
		/*
		 * UserRoleDto userRoleEntity = new UserRoleDto(); userRoleEntity.setUserId(userId);
		 * userRoleEntity.setRoleId(roleId); userRoleEntity.setMerchantId(user.getMerchantId());
		 * userRoleEntity.setRemark("系统导入"); userRoleEntity.setCreateUserId(user.getId());
		 * userRoleEntity.setUpdateTime(new Date()); userRoleEntity.setDelFlag("0"); userRoleEntity.setCreateTime(new
		 * Date()); userRoleServiceFacade.save(userRoleEntity);
		 */
	}
	
	
	public void saveImportLog(String title,String result ,String remark,Long sort,String no,User user){
		ImportlogDto logdto = new ImportlogDto();
		logdto.setTitle(title);
		logdto.setResult(result);
		logdto.setRemark(remark);
		logdto.setSort(sort);
		logdto.setCreateTime(new Date());
		logdto.setDelFlag("0");
		logdto.setMerchantId(user.getMerchantId());
		logdto.setBatchCode(no);
		importlogServiceFacade.save(logdto);
	}
	
	/**
	* 方法描述 : 验证导入模版是否与模版类型相同
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： ProjectImportController.java
	* 版本： v1.0
	* 创建时间： 2016年8月22日 下午12:24:28
	* @param xssfSheet
	* @param type
	* @return boolean
	 */
	public String vaildExcelType(Sheet xssfSheet,String type){
		String value = xssfSheet.getRow(0).getCell(1).toString();
		String no = SequencesGenerator.getUUID("BTN");
		//导入的是公寓模版,而类型却不是公寓
		if(!value.equals(ExcelTypeEnum.ExcelTypeEnum_1.getValue())&&type.equals(HouseTypeEnum.HOUSETYPE_0.getCode())){
			saveImportLog("导入错误", "0", "请导入正确的公寓模版!", 0L, no, ShiroUtil.getCurrentUser());
			return no;
		}else if(!value.equals(ExcelTypeEnum.ExcelTypeEnum_2.getValue())&&type.equals(HouseTypeEnum.HOUSETYPE_1.getCode())){
			saveImportLog("导入错误", "0", "请导入正确的别墅模版!", 0L, no, ShiroUtil.getCurrentUser());
			return no;
		}else if(!value.equals(ExcelTypeEnum.ExcelTypeEnum_3.getValue())&&type.equals(HouseTypeEnum.HOUSETYPE_2.getCode())){
			saveImportLog("导入错误", "0", "请导入正确的车位模版!", 0L, no, ShiroUtil.getCurrentUser());
			return no;
		}
		return null;
	}
}
